<style lang="scss" src="./index.scss"></style>
<template>
    <div class="ask-image-box">
        <img class="ask-image__inner" v-bind="$attrs" :src="currentSrc"/>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";

@Component
export default class AskImage extends Vue {
    @Prop({
        type: String,
        default: ""
    }) readonly src!: string;

    @Prop({
        type: String,
        default: require("@/assets/error.png")
    }) readonly errorSrc!: string;

    @Prop({
        type: String,
        default: require("@/assets/error.png")
    }) readonly loadSrc!: string;

    currentSrc = "";
    onError(e: any) {
        this.currentSrc = this.errorSrc;
        this.$emit("error", e);
    }

    @Watch("src", { immediate: true })
    loadImage() {
        this.currentSrc = this.loadSrc;
        const img = new Image();
        img.src = this.src;
        img.onload = e => {
            this.onLoad(e);
        };
        img.onerror = e => {
            this.onError(e);
        };
    }

    onLoad(e: any) {
        this.currentSrc = this.src;
        this.$emit("load", e);
    }
}
</script>
